package com.xuzhiguang.lightnat.server.api.controller;

import com.xuzhiguang.lightnat.common.manager.ControlChannelManager;
import com.xuzhiguang.lightnat.server.api.domain.*;
import com.xuzhiguang.lightnat.server.core.exception.NatClientNotFoundException;
import com.xuzhiguang.lightnat.server.wrap.bean.Client;
import com.xuzhiguang.lightnat.server.wrap.manager.NatClientManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Validated
@RestController
@RequestMapping("/api/client")
public class ClientController {

    private final NatClientManager natClientManager;

    @Autowired
    public ClientController(NatClientManager natClientManager) {
        this.natClientManager = natClientManager;
    }


    @GetMapping("/list")
    public ApiResponse<ClientListResponse> list() {
        List<Client> list = natClientManager.listAllClient();
        List<ClientListResponse.Item> items = list.stream().map(client -> {
            ClientListResponse.Item item = new ClientListResponse.Item();
            BeanUtils.copyProperties(client, item);

            item.setIsOnline(ControlChannelManager.getChannel(client.getId()) != null);
            item.setId(client.getId().toString());
            return item;
        }).collect(Collectors.toList());

        ClientListResponse response = new ClientListResponse();
        response.setList(items);
        return new ApiResponse<>(ResponseEnum.SUCCESS, response);

    }

    @PostMapping("/add")
    public ApiResponse<ClientAddResponse> add(@Valid @RequestBody ClientAddRequest request) {

        Client client = new Client();
        BeanUtils.copyProperties(request, client);
        client = natClientManager.addClient(client);

        ClientAddResponse response = new ClientAddResponse();
        BeanUtils.copyProperties(client, response);

        return new ApiResponse<>(ResponseEnum.SUCCESS, response);
    }

    @PostMapping("/{clientId}/modify")
    public ApiResponse<Object> modify(@Valid @RequestBody ClientModifyRequest request, @PathVariable("clientId") long clientId) throws NatClientNotFoundException {
        Client client = new Client();
        BeanUtils.copyProperties(request, client);
        client.setId(clientId);
        natClientManager.modifyClient(client);

        return new ApiResponse<>(ResponseEnum.SUCCESS);
    }

    @DeleteMapping("/{clientId}")
    public ApiResponse<Object> delete(@PathVariable("clientId") long clientId) throws NatClientNotFoundException {
        natClientManager.deleteClient(clientId);
        return new ApiResponse<>(ResponseEnum.SUCCESS);
    }

}
